/**
 * 
 */
package br.embedded.socialapp.business;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

import org.jgrapht.Graph;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import br.embedded.socialapp.domain.Usuario;

/**
 * @author daniel
 *
 */
public class UserGenerator
{
	
	public static List<Usuario> generateUsers(int count)
	{
		List<Usuario> usersList = new ArrayList<Usuario>();
		
		for (int i = 1; i <= count; i++)
		{
			Usuario usuario = new Usuario();
			usuario.setLogin("user"+i);
			usuario.setPasswd("123456");
			usuario.setFirstName("User"+i);
			usuario.setLastName("MySocial"+i);
			usersList.add(usuario);
		}
		
		return usersList;
	}
	
	public static int getUser(List<Usuario> users)
	{
		Random random = new Random();
		return random.nextInt(users.size());
	}
	
	public static Graph<Usuario, DefaultEdge> buildFriendshipGraph(List<Usuario> usersList, int friendsCount)
	{
		Hashtable<String, Integer> friendsHash = new Hashtable<String, Integer>();
		
		UndirectedGraph<Usuario, DefaultEdge> graph = new SimpleGraph<Usuario, DefaultEdge>(DefaultEdge.class);
		
		for (Usuario u : usersList) {
			graph.addVertex(u);
			friendsHash.put(u.getLogin(), 0);
		}
		
		while (usersList.size() > 0)
		{
			int index = UserGenerator.getUser(usersList);
			Usuario u1 = usersList.get(index);
			usersList.remove(u1);
			
			int count = 0;
			
			for (int j = 0; j < usersList.size(); j++)
			{
				Usuario friend = usersList.get(j);
					
				if (!u1.getLogin().equalsIgnoreCase(friend.getLogin()) 
						&& (!graph.containsEdge(u1, friend) || !graph.containsEdge(friend, u1)))
				{
					if (friendsHash.get(u1.getLogin()) < friendsCount && friendsHash.get(friend.getLogin()) < friendsCount)
					{
						graph.addEdge(u1, friend);
						int total1 = friendsHash.get(u1.getLogin()) + 1;
						int total2 = friendsHash.get(friend.getLogin()) + 1;
						friendsHash.put(u1.getLogin(), new Integer(total1));
						friendsHash.put(friend.getLogin(), new Integer(total2));
						count++;
						
						if (count == friendsCount)
						{
							break;
						}
					}
				}
			}
		}
		
		return graph;
	}
}
